package gov.nist.ssd.swqb.core.search;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import com.hp.hpl.jena.rdf.model.RDFNode;

class MergedSearch implements Search {

  private List<Search> searches;
  
  /**
   * 
   * @param searchList multiple Search
   */
	public MergedSearch(Search ...searchList) {
		searches = new ArrayList<Search>();
		for(Search search : searchList) {
			if(search!=null) {
				searches.add(search);
			}
		}
	}

  @Override
  public Iterator<RDFNode> iterator() {
    return new Iterator<RDFNode>() {

      private Iterator<Search> searchIterator = searches.iterator();
      private Iterator<RDFNode> currentIterator = null;
      
      @Override
      public boolean hasNext() {
        if(currentIterator == null) {
          if(searchIterator.hasNext()) {
            currentIterator = searchIterator.next().iterator();
          } else {
            return false;
          }
        }
        
        if(currentIterator.hasNext()) {
          return true;
        } else {
          currentIterator = null;
          return hasNext();
        }
      }

      @Override
      public RDFNode next() {
        if(hasNext()) {
          return currentIterator.next();
        } else {
          throw new NoSuchElementException();
        }
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
      
    };
  }

  @Override
  public boolean isValid() {
    boolean res = true;
    
    for(Search s : searches) {
      res = res && s.isValid();
    }
    
    return res;
  }

  @Override
  public String getErrorDescription() {
    return "";
  }
}
